import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';

import AndroidModule from 'src/utils/AndroidConnent'
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";
import { getImgUrl } from '../../utils/ComFunction'
import SelectAttachmentPop from './SelectAttachmentPop';
import BigImageContainer from '../../components/Tool/BigImageContainer';


const screenW = Dimensions.get('window').width;
const isIos = Platform.OS == 'ios';
const imgWidth = (screenW - 16 - 16 - 30 - 10) / 4;


/**
 * 合同附件组件
 */
export default class ContractAttachment extends Component {

    constructor(props) {
        super(props);
        this.state = {
            attachmentFileList: [],
            localImgList: [],
            showPop: false,
            maintenanceReport: '',
            checkReport: '',
            isOnlyShow: this.props.isOnlyShow,//是否只是显示附件
            carPics: [],
            showBigImageContainer: false,
            currImgIndex: 0,
        }
    }




    componentWillMount() {
        this.uploadSuccessListener = DeviceEventEmitter.addListener('uploadSuccess', e => {

            console.log('uploadSuccess', e)

            let picUrls = null
            if (isIos) {
                picUrls = e.picUrls
            } else {
                let picObj = JSON.parse(e)
                picUrls = picObj.picUrls
            }
            if (picUrls.length > 0) {
                let temp = []
                this.state.localImgList.map((item, index) => {
                    if (item != '') {
                        temp.push(item)
                    }

                })
                let picUrlArray = temp.concat(picUrls)
                picUrlArray.push('')
                this.setState({
                    localImgList: picUrlArray
                })
            }
        })

        this.commonEventLinster = DeviceEventEmitter.addListener('commonEvent', e => {
            if(e.eventName == 'selectAttachmentResultListener'){
                let temp = []
                this.state.attachmentFileList.map((item, index) => {
                if(item.title == '检测报告' || item.title == '维保报告'){
                    temp.push(item)
                }
                })
                let picUrlArray = JSON.parse(e.resultList)
                //选择附件回调
                this.setState({
                    attachmentFileList: temp.concat(picUrlArray)
                })
            }
           
        });
    }

    componentWillUnmount() {
        this.uploadSuccessListener.remove();
        this.commonEventLinster.remove();
    }

    componentDidMount() {
        if (this.state.isOnlyShow) {
            console.log('attachmentFiles-onlyShow', this.props.attachmentFileList)
            this.setState({
                localImgList: this.props.localImgList,
                attachmentFileList: this.props.attachmentFileList
            })
        } else {
            this.setState({
                localImgList: ['']
            })
        }
    }

    componentDidUpdate(prevProps) {
        // if (prevProps.carId) {
        //     this.setState({
        //         carId: prevProps.carId
        //     })
        // }
    }



    render() {
        return (
            <View style={styles.container}>

                <View style={styles.titleContain}>
                    <Text style={styles.titleText}>合同附件</Text>
                </View>
                <View style={styles.addBtnContain}>
                    <Text style={styles.titleText2}>车辆关联附件</Text>

                    {!this.state.isOnlyShow ?
                        <TouchableOpacity
                            style={styles.contractInfomationRight}
                            activeOpacity={0.8}
                            onPress={() => {
                                if (!this.props.carId) {
                                    ToastToUser('请先选择车辆')
                                    return
                                }
                                this.setState({
                                    showPop: true
                                })

                            }}
                        >
                            <Text style={styles.contractInfomationTips}>添加附件</Text>
                            <Image source={require('source/image/electron/contractchooseadd.png')} style={styles.contractInfomationImg} />
                        </TouchableOpacity>
                        : null
                    }

                </View>

                <View>
                    {this.state.attachmentFileList.map((item, index) => {
                        let that = this
                        return (
                            <View style={styles.itemContain} key={index}>
                                <Text style={styles.titleText2}>{item.title}</Text>

                                <View style={{ height: '100%', flexDirection: 'row' }}>
                                    <TouchableOpacity
                                        style={styles.imgBtnContain}
                                        onPress={() => {
                                            //查看附件
                                            if (item.title == '车辆行驶证' || item.title == '车辆登记证' || item.title == '身份证' || item.title == '其他证件' || item.title.includes('其他图片')) {
                                                let preObj = {
                                                    index: 0,
                                                    imgList: item.value
                                                }

                                                let carPics = []
                                                if (item.value) {
                                                    item.value.map((picUrl) => {
                                                        carPics.push({ url: getImgUrl(picUrl) })
                                                    })
                                                }

                                                this.setState({
                                                    carPics: carPics,
                                                    currImgIndex: 0,
                                                    showBigImageContainer: true
                                                })
                                            } else {

                                                this.previewPdf(item)
                                                
                                            }
                                        }}>
                                        <Image source={require('source/image/electron/search.png')} style={styles.imgStyle} />
                                    </TouchableOpacity>

                                    {this.state.isOnlyShow ? null
                                        :
                                        <TouchableOpacity
                                            style={styles.imgBtnContain}
                                            onPress={() => {
                                                //删除附件
                                                let temp = this.state.attachmentFileList
                                                temp.splice(index, 1)
                                                this.setState({
                                                    attachmentFileList: temp
                                                })
                                            }}>
                                            <Image source={require('source/image/electron/searchClose.png')} style={styles.imgStyle} />
                                        </TouchableOpacity>
                                    }

                                </View>
                            </View>
                        )
                    })}
                </View>

                <View style={{ height: 0.5, backgroundColor: '#E4E4E4', marginTop: 12 }}></View>

                <Text style={[styles.titleText2, { marginTop: 12 }]}>本地图片</Text>

                <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginBottom: 12 }}>
                    {this.state.localImgList.map((item, index) => {
                        if (item == '') {
                            return (
                                <TouchableOpacity key={index}
                                    onPress={() => {
                                        let obj = {
                                            num: 9
                                        }
                                        AndroidModule.openPhoto(obj)
                                    }}>
                                    <Image source={require('source/image/electron/addimg.png')} style={styles.localImgStyle} />
                                </TouchableOpacity>
                            )
                        } else {
                            return (
                                <View key={index}>
                                    <Image style={styles.localImgStyle} source={{ uri: getImgUrl(item) }}></Image>
                                    {this.state.isOnlyShow ? null
                                        :
                                        <TouchableOpacity
                                        style={{position:'absolute',top:5,right:5}}
                                        onPress={() => {
                                            let temp = this.state.localImgList
                                            temp.splice(index, 1)
                                            this.setState({
                                                localImgList: temp
                                            })
                                        }}>
                                        <Image source={require('source/image/electron/chooseclose.png')} style={styles.imgStyle} />
                                    </TouchableOpacity>
                                    }
                                    
                                </View>
                                
                            )
                        }

                    })}
                </View>

                {
                    this.state.showPop ?
                        <SelectAttachmentPop
                            maintenanceRecordPdf={this.props.maintenanceRecordPdf}
                            detectionReportPdf={this.props.detectionReportPdf}
                            onClose={() => {
                                this.setState({
                                    showPop: false
                                })
                            }}
                            resultCallback={(result) => {
                                this.setState({
                                    showPop: false
                                }, function() {
                                    if (result == 1) {//检测报告
                                        let obj = {
                                            title: '检测报告',
                                            value: [this.props.detectionReportPdf]
                                        }
                                        let temp = this.state.attachmentFileList
                                        temp.push(obj)
                                        this.setState({
                                            attachmentFileList: temp
                                        })
                                    } else if (result == 2) {//维保报告
                                        let obj = {
                                            title: '维保报告',
                                            value: [this.props.maintenanceRecordPdf]
                                        }
                                        let temp = this.state.attachmentFileList
                                        temp.push(obj)
                                        this.setState({
                                            attachmentFileList: temp
                                        })
                                    } else if (result == 3) {
                                        setTimeout(() => {
                                            let params = {
                                                carId: this.props.carId,
                                                fileList: JSON.stringify(this.state.attachmentFileList)
                                            }
                                            this.props.navigation.navigate('AttachmentImagePage', params)
                                        }, 700);
                                    }
                                })
                            }}
                        />
                        :
                        null
                }

                <Loading onRef={(ref) => (this.uploadLoading = ref)} />

                {
                    this.state.showBigImageContainer ?
                        <BigImageContainer
                            idx={this.state.currImgIndex}
                            images={this.state.carPics}
                            closeHandler={(index) => {
                                this.setState({
                                    currImgIndex: index,
                                    showBigImageContainer: false
                                })
                            }}
                        />
                        :
                        null
                }
            </View>
        );
    }

    previewPdf(item){
        let tempUrl = ''
        if(item.title == '检测报告'){
            tempUrl = item.value[0]
        }else{
            tempUrl = item.value[0]
        }
        let params = {
            fileDownloadUrl:  tempUrl,
            templateId: '-1'
        }

        navigation.navigate('PrivewContractPage', params)
    }

    getAttachmentFiles() {

        let localImgList = this.state.localImgList
        let localTemp = []
        localImgList.map((item, index) => {
            if (item != '') {
                localTemp.push(item)
            }
        })

        let attachmentFileResult = {
            attachmentFileList: this.state.attachmentFileList,
            localImgList: localTemp
        }

        return attachmentFileResult
    }

}

const styles = StyleSheet.create({
    container: {
        width: screenW,
        flexDirection: 'column',
        flex: 1,
        paddingLeft: 16,
        paddingRight: 16
    },

    titleText: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
    },
    titleText2: {
        fontSize: 14,
        color: '#333333',
    },
    titleContain: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5,
        height: 48,
        flexDirection: 'row',
        alignItems: 'center',
    },
    addBtnContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginTop: 10,
        marginBottom: 10
    },
    contractInfomationRight: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    contractInfomationImg: {
        width: 25,
        height: 25,
        marginLeft: 7
    },
    contractInfomationTips: {
        fontSize: 14,
        color: '#666666'
    },
    itemContain: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
        justifyContent: 'space-between',
        borderRadius: 4,
        backgroundColor: '#F5F5F5',
        height: 40,
        paddingLeft: 10,
        paddingRight: 10
    },
    imgBtnContain: {
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row',

        marginLeft: 12
    },
    imgStyle: {
        width: 15,
        height: 15,
    },

    localImgStyle: {
        width: imgWidth,
        height: imgWidth,
        borderRadius: 4,
        marginRight: 10,
        marginTop: 12
    }


})